package com.xtq.countclass.service.impl;

import com.xtq.countclass.dao.GroupeDao;
import com.xtq.countclass.dao.RecordDao;
import com.xtq.countclass.dao.UserDao;
import com.xtq.countclass.entity.Groupe;
import com.xtq.countclass.entity.Record;
import com.xtq.countclass.entity.User;
import com.xtq.countclass.service.UserService;
import lombok.val;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.swing.*;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 学生表;(User)表服务实现类
 *
 * @author makejava
 * @since 2024-03-06 00:10:29
 */
@Service("userService")
public class UserServiceImpl implements UserService {
	@Resource
	private UserDao userDao;
	@Resource
	private RecordDao recordDao;
	
	/**
	 * 通过ID查询单条数据
	 *
	 * @param id 主键
	 * @return 实例对象
	 */
	@Override
	public User queryById(String id) {
		return this.userDao.queryById(id);
	}
	
	@Override
	public List<User> queryByGroupID(String id) {
		return userDao.queryByGroupID(id);
	}


	
	/**
	 * 新增数据
	 *
	 * @param user 实例对象
	 * @return 实例对象
	 */
	@Override
	public User insert(User user) {
		this.userDao.insert(user);
		recordDao.insert(new Record(user.getGroupid(), "admin", 0, LocalDateTime.now().toString(), 0,"新增用户:"+user.getId()+user.getName()+"所属小组id:"+user.getGroupid()));
		return user;
	}
	
	/**
	 * 修改数据
	 *
	 * @param user 实例对象
	 * @return 实例对象
	 */
	@Override
	public User update(User user) {
		this.userDao.update(user);
		
		
		return this.queryById(user.getId());
	}
	
	/**
	 * 通过主键删除数据
	 *
	 * @param id 主键
	 * @return 是否成功
	 */
	@Override
	public boolean deleteById(String id) {
		
		boolean b = this.userDao.deleteById(id) > 0;
		recordDao.insert(new Record(null, "admin", 0, LocalDateTime.now().toString(), 0,"删除个人:"+id));
		return b;
		
	}
	
	@Override
	public User isClassify(String id, String password) {
		User user;
		if ((user = userDao.queryById(id)) != null) {
			return user.getPassword()
			           .equals(password)?user:null;
		}
		return null;
	}
	@Override
	public boolean isAdmin(String id, String password) {
		val classify = isClassify(id, password);
		if (classify==null)return false;
		return "admin".equals(classify.getType());
	}
	
	@Override
	public void deleteByGroupId(String groupid) {
		List<User> users = userDao.queryByGroupID(groupid);
		
		userDao.deleteByGroupId(groupid);
		recordDao.insert(new Record(groupid, "admin", 0, LocalDateTime.now().toString(), 0,"删掉小组的所有成员:"+ users.stream().map(User::getName).toList()));
	}
	
	@Override
	public Boolean modifyPassword(String pwd) {
		
		return userDao.updatePwd(pwd);
	}
	
}
